package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-01
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    private final static Integer TOKEN_TIME = 120;

    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 管理员登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserLoginDto dto) {
        //条件查询
        LambdaQueryWrapper<AdUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AdUser::getName,dto.getName());
        AdUser adUser = this.getOne(lqw);
        //判断adUser是否存在
        if (adUser == null){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        String passwordDB = adUser.getPassword();
        String password = dto.getPassword();
        boolean b = encoder.matches(password, passwordDB);
        if (!b){
            //如果密码不对  抛出异常
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //设置token
        Map<String,Object> map = new HashMap<>();
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), TOKEN_TIME);
        map.put("token",token);
        AdUserDto adUserDto = new AdUserDto();
        BeanUtils.copyProperties(adUser,adUserDto);
        map.put("user",adUserDto);
        return ResponseResult.ok(map);


    }
}
